package com.timothy.android;

import com.timothy.question.STTwoButtonAlpha;
import com.timothy.service.BackLightService;
import com.timothy.service.MessageReceiveService;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.Toast;

public abstract class BaseActivity extends Activity {
	private static final String LOG_TAG = "BaseActivity";
	public static final int ITEM0 = Menu.FIRST;// 系统值
	public static final int ITEM1 = Menu.FIRST + 1;
	public static final int ITEM2 = Menu.FIRST + 2;
	public static final int ITEM3 = Menu.FIRST + 3;
	
	private float screenStartBrightness;
	private Messenger bsrMessenger = new Messenger( new BSIncomingHandler() );
    private Messenger bssMessenger = null;	
    private Messenger rsrMessenger = new Messenger( new RSIncomingHandler() );
    private Messenger rssMessenger = null;
    
	public float getScreenStartBrightness() {
		return screenStartBrightness;
	}

	public void setScreenStartBrightness(float screenStartBrightness) {
		this.screenStartBrightness = screenStartBrightness;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
	    //keep screen no locked
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        
        //set default orientation
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
 
		//record screen start brightness
	    WindowManager.LayoutParams lp = getWindow().getAttributes();     
	    setScreenStartBrightness(lp.screenBrightness);		      
	    Log.i(LOG_TAG,"Screen Start Brightness:" + getScreenStartBrightness());
	    
	    
	    //bind screen brightness service
	    doBindService();
	    
	}
	    
	//屏幕触摸事件
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		//恢复屏幕亮度
		Log.i(LOG_TAG,"Recover Screen Start Brightness.");
		Log.i(LOG_TAG,"Get Screen Start Brightness:" + getScreenStartBrightness());
		
		WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = getScreenStartBrightness();
        getWindow().setAttributes(lp);
        
        Message msg = Message.obtain(null, BackLightService.MSG_TOUCH_SCREEN);
        msg.replyTo = bsrMessenger;
        try {
        	bssMessenger.send(msg);
        } catch (RemoteException e) {
        }
        
		return super.onTouchEvent(event);
	}

	//Activity 销毁时的操作
	protected void onDestroy() {
        super.onDestroy();
		//恢复屏幕亮度
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = getScreenStartBrightness();
        getWindow().setAttributes(lp);
    }
	
	static int x = 0;
	protected void onResume(){
		super.onResume();
		Log.i("BaseActivity","x:"+x++);
		doBindService();
	}
	
	static int y = 0;
	protected void onPause(){
		super.onPause();
		Log.i("BaseActivity","y:"+y++);
		doUnbindService();
	}

	private boolean bsIsBound;
	private boolean rsIsBound;
	
	private void doBindService() {
        bindService(new Intent(this, BackLightService.class), bsConnection, Context.BIND_AUTO_CREATE);
        bindService(new Intent(this, MessageReceiveService.class), rsConnection, Context.BIND_AUTO_CREATE);
    }

    protected void doUnbindService() {
        if (bsIsBound) {
            unbindService(bsConnection);
            bsIsBound = false;
        }
        
        if (rsIsBound) {
            // Detach our existing connection.
            //unbindService(rsConnection);
            rsIsBound = false;
        }
    }
	
	private ServiceConnection bsConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
        	 bssMessenger = new Messenger(service);
             try {
                 Message msg = Message.obtain(null, BackLightService.MSG_REGISTER_CLIENT);
                 msg.replyTo = bsrMessenger;
                 bssMessenger.send(msg);
             } catch (RemoteException e) {
             }
        
            bsIsBound = true;
        }

        public void onServiceDisconnected(ComponentName className) {
        	 Message msg = Message.obtain(null, BackLightService.MSG_UNREGISTER_CLIENT);
             msg.replyTo = bsrMessenger;
             try {
            	 bssMessenger.send(msg);
             } catch (RemoteException e) {
             }
        }
    };
    
    private ServiceConnection rsConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
        	 rssMessenger = new Messenger( service );
             // We want to monitor the service for as long as we are connected to it.
             try {
                 Message msg = Message.obtain(null, MessageReceiveService.MSG_REGISTER_CLIENT);
                 msg.replyTo = rsrMessenger;
                 rssMessenger.send(msg);
             } catch (RemoteException e) {
                 // In this case the service has crashed before we could even
                 // do anything with it; we can count on soon being
                 // disconnected (and then reconnected if it can be restarted)
                 // so there is no need to do anything here.
             }
        
            rsIsBound = true;
            // Tell the user about this for our demo.
            Toast.makeText( getBaseContext(), R.string.message_receive_service_connected, Toast.LENGTH_SHORT).show();
        }
        
        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            // Because it is running in our same process, we should never
            // see this happen.
        	 Message msg = Message.obtain(null, MessageReceiveService.MSG_UNREGISTER_CLIENT);
             msg.replyTo = rsrMessenger;
             try {
            	 rssMessenger.send(msg);
             } catch (RemoteException e) {
                 // In this case the service has crashed before we could even
                 // do anything with it; we can count on soon being
                 // disconnected (and then reconnected if it can be restarted)
                 // so there is no need to do anything here.
             }
            Toast.makeText( getBaseContext(), R.string.message_receive_service_disconnected, Toast.LENGTH_SHORT).show();
        }
    };

    class BSIncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
//        	Log.i(LOG_TAG,"msg.what:"+msg.what);
        	
            switch (msg.what) {
                case BackLightService.MSG_DARK:
		        	//使屏幕的亮度变暗
		        	WindowManager.LayoutParams lp = getWindow().getAttributes();
	        		lp.screenBrightness = 0.2f;
		            getWindow().setAttributes(lp);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
    
    class RSIncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
    		Log.i("BaseStations",""+msg.obj);
        	processMessage( msg.what, (String)msg.obj );
        	/*
            switch (msg.what) {
                case MessageReceiveService.MSG_QUESTION:        				
                	if(msg.obj instanceof STTwoButtonAlpha ) {
                		STTwoButtonAlpha st = (STTwoButtonAlpha) msg.obj;
                		Log.i("message", msg.obj.toString());
        				Intent intent = new Intent();
        				intent.putExtra("STTwoButtonAlpha", st.getXmlString());
        			    intent.setClass( getBaseContext(), LayoutA.class);
        			    startActivity(intent);
                	}
                    break;
                case MessageReceiveService.MSG_BASE_STATION: 
                	{
                	String bsList = (String)msg.obj;
                	Intent intent = new Intent();
                	intent.putExtra("value", bsList);
                	intent.setClass( getBaseContext(), BaseStations.class);
                	startActivity(intent);
                	}
                	break;
                case MessageReceiveService.MSG_SHORT_MESSAGE:
                	String state = (String)msg.obj;
                	if( "successfully".equals( state ) )
                		Toast.makeText( getBaseContext(), R.string.message_receive_service_connected, Toast.LENGTH_SHORT).show();
                	else {
                		Toast.makeText( getBaseContext(), R.string.message_password_invalid, Toast.LENGTH_SHORT).show();
                		Intent intent = new Intent();
	                	intent.setClass( getBaseContext(), BaseStations.class);
                	}	
                default:
                    super.handleMessage(msg);
            }
            */
        }
    }
    
    protected abstract void processMessage( int what, String content);
    
	protected void mobileDefaultSetting(){
	}
	
	protected void ShowDialog(String msg) {
		new AlertDialog.Builder(this).setTitle("提示").setMessage(msg)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).show();
	}
	
	
	//-------------------create menu---------------------
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, ITEM0, 0, "Stations");
		menu.add(0, ITEM1, 0, "Home");
		menu.add(0, ITEM2, 0, "Quit");
		menu.add(0, ITEM3, 0, "About");
		menu.findItem(ITEM1);// 可以设置按钮的背景
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case ITEM0:actionClickMenuItem1();break;
			case ITEM1:actionClickMenuItem2();break;
			case ITEM2:actionClickMenuItem3();break;
			case ITEM3:actionClickMenuItem4();break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void actionClickMenuItem1() {
		Intent intent = new Intent();
	    intent.setClass(this,BaseStations.class);
	    startActivity(intent);
	}

	private void actionClickMenuItem2() {
		Intent intent = new Intent();
	    intent.setClass(this,HomeActivity.class);
	    startActivity(intent);
	}

	private void actionClickMenuItem3() {
		Intent intent = new Intent();
	    intent.setClass(this,LoginActivity.class);
	    startActivity(intent);
	}

	private void actionClickMenuItem4() {

	}
}
